package Step;

import d1_create_thread.MyThread;

/**
 * @author Cjj
 * 顺序输出 A B C
 * 利用多线程控制三个线程 依照先后顺序输出
 */
public class Task {
    public static void main(String[] args) throws InterruptedException {
        /********* Begin *********/
        //在这里创建线程, 开启线程
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();

        MyThread ta= new MyThread("A",c,a);
        MyThread tb= new MyThread("B",a,b);
        MyThread tc= new MyThread("C",b,c);
        ta.start();
        ta.sleep(100);
        tb.start();
        tb.sleep(100);
        tc.start();
        tc.sleep(100);
        /********* End *********/
    }
}

class MyIThread extends Thread{
    /********* Begin *********/
    private String threadName;
    private Object prev;
    private Object self;
    public MyIThread(String name, Object prev, Object self){
        this.threadName = name;
        this.prev = prev;
        this.self = self;
    }
    //synchronized 关键字 在执行一个发法或者代码块的时候 加上synchronized保证线程安全
    public void run(){
        int count=5;
        while (count>0){
            synchronized (prev){
                synchronized (self){
                    System.out.println("Java Thread"+this.threadName+this.threadName);
                    count--;
                    self.notify();//notify()方法唤醒等待的线程
                }
                try {
                    prev.wait();//wait()方法使当前线程等待，直到另一个线程调用了该对象的notify()方法或notifyAll()方法
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
        System.exit(0);//退出程序
    }
    /********* End *********/
}
